package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.client.SsoClient;
import cn.itsource.hrm.domain.Employee;
import cn.itsource.hrm.domain.Sso;
import cn.itsource.hrm.mapper.EmployeeMapper;
import cn.itsource.hrm.service.IEmployeeService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.StrUtils;
import cn.itsource.hrm.util.UserType;
import cn.itsource.hrm.util.encrypt.MD5;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yhptest
 * @since 2020-06-22
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private SsoClient ssoClient;
    //对员工做增删改都要同步操作sso
    @Override
    public boolean insert(Employee entity) {
        //添加完成后返回id
        AjaxResult ajaxResult = ssoClient.addOrUpdate(emp2Sso(entity));
        Long ssoId = Long.valueOf(ajaxResult.getResultObj().toString());

        entity.setSsoId(ssoId);
        employeeMapper.insert(entity);
        return true;
    }

    private Sso emp2Sso(Employee employee) {
        Sso sso = new Sso();
        sso.setId(employee.getSsoId());
        sso.setCreateTime(System.currentTimeMillis());
        sso.setUsername(employee.getUsername());
        sso.setNickName(StrUtils.getComplexRandomString(4));
        sso.setEmail(employee.getEmail());
        sso.setPhone(employee.getTel());
        sso.setUserType(UserType.USERTYPE_EMPLOYEE);
        sso.setSecLevel(0);
        //未激活-1 已激活1 已手机实名认证2 一个值表示多个状态-二进制表示法
        sso.setBitState(1L);
        String salt = StrUtils.getComplexRandomString(32);
        String secretyPwd = MD5.getMD5(employee.getPassword()+salt);
        sso.setSalt(salt);
        sso.setPassword(secretyPwd);
        return sso;
    }

    @Override
    public boolean updateById(Employee entity) {
        employeeMapper.updateById(entity);

        //设置sso有id就是修改
        ssoClient.addOrUpdate(emp2Sso(entity));
        return true;
    }

    @Override
    public boolean deleteById(Serializable id) {
        ssoClient.delete(employeeMapper.selectById(id).getSsoId());
        employeeMapper.deleteById(id);
        return true;
    }
}
